import { PageConfig } from '@/types/pageConfig'
import { RouteItem } from '@/types/route'
/**
 * 将一级路由组装成树路由
 * @param routes 一级路由
 * @returns
 */
function routesToTree(routes: RouteItem[]) {
  const mapNodes: Record<string, RouteItem> = {}
  const treeList: RouteItem[] = []

  routes.forEach((item) => {
    if (item.redirect) {
      mapNodes[item.path] = item
    }
  })
  routes.forEach((item) => {
    const parent = mapNodes[item.meta!.parentKey!]
    if (parent) {
      if (parent.children) {
        parent.children.push(item)
        parent.redirect = parent.children[0].path
      } else {
        parent.children = [item]
        parent.redirect = parent.children[0].path
      }
    } else {
      treeList.push(item)
    }
  })
  return treeList
}

/**
 * 自动注册路由
 * @returns
 */
export const autoRegisterRoute = () => {
  const components = import.meta.glob('@/modules/**/*.vue')
  const configs: Record<string, PageConfig> = import.meta.glob('@/modules/**/*.config.ts', {
    eager: true,
    import: 'default'
  })

  const autoRoutes: RouteItem[] = []
  for (const key in configs) {
    let pathArr = key.split('/')
    pathArr = pathArr.slice(3, pathArr.length - 1)
    const path = '/' + pathArr.join('/')
    const name = pathArr.join('-')
    const comKey = key.replace('.config.ts', '.vue')
    const route: RouteItem = {
      path,
      name,
      meta: configs[key].routeMeta
    }
    if (components[comKey]) {
      route.component = components[comKey]
    } else {
      route.redirect = 'children'
      route.children = []
    }
    autoRoutes.push(route)
  }
  console.log(autoRoutes)

  autoRoutes.sort((item, nextItem) => item.meta!.sort - nextItem.meta!.sort)
  const finalRoutes = routesToTree(autoRoutes)

  return finalRoutes
}
